﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TjZheng.Framework;
using TjZheng.CMS.Process;
using TjZheng.Power.Business;
using TjZheng.Power.DataEntity;
using TjZheng.Controls;
using TjZheng.Base;
using TjZheng.CMS.Process.Business;
using TjZheng.Redis;
using TjZheng.Power.RedisEntity;

namespace TjZheng.CMS.Controllers
{
    public partial class PowerInfoController : CMSController
    {
        BizPowerInfo objBizPowerInfo { get; set; }
        public PowerInfoController()
        {
            objBizPowerInfo = new BizPowerInfo();
        }
        /// <summary>
        /// 模块配置
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 模块列表
        /// </summary>
        /// <returns></returns>
        public ActionResult PowerInfoIndex()
        {
            return View();
        }
        /// <summary>
        /// 模块列表数据
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        [QueryMsSqlFilter("ParentId")]
        [AuthorizeFilter(PowerType.CheckLogin)]
        public ActionResult ListJson(int page, int rows)
        {
            return Json(objBizPowerInfo.GetPageResult(page - 1, rows, QueryResult.Condition, QueryResult.Parameters, "SortIndex asc"));
        }
        /// <summary>
        /// 权限树
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AuthorizeFilter(PowerType.CheckLogin)]
        public ActionResult TreeJson(long id)
        {
            //easyui的树结构一定是数组才可以
            PowerProcess objPowerProcess = new PowerProcess();
            return Json(objPowerProcess.BindPowerInfoTrees(id, true));
        }
        /// <summary>
        /// 除根节点权限列表树
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AuthorizeFilter(PowerType.CheckLogin)]
        public ActionResult TreeListJson(long id)
        {
            PowerProcess objPowerProcess = new PowerProcess();
            return Json(objPowerProcess.BindPowerInfoTreeListWithoutUnDisplay(id, false));
        }
        /// <summary>
        /// 除父节点和按钮的子权限列表
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AuthorizeFilter(PowerType.CheckLogin)]
        public ActionResult ChildrenWithoutButton(long id)
        {
            PowerProcess objPowerProcess = new PowerProcess();
            return Json(objPowerProcess.BindPowerInfoChildrenWithoutButton(id, false));
        }
        /// <summary>
        /// 权限编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult EditPage(long? id)
        {
            PowerInfo objPowerInfo = null;
            if (id.HasValue)
            {
                objPowerInfo = objBizPowerInfo.GetRecord(id.Value);
            }
            else
            {
                objPowerInfo = new PowerInfo();
            }
            return View(objPowerInfo);
        }
        //[ValidateAntiForgeryToken]
        /// <summary>
        /// 权限保存
        /// </summary>
        /// <param name="objProvide"></param>
        /// <returns></returns>
        public ActionResult Save(PowerInfo objProvide)
        {
            InvokeResult objInvokeResult = new InvokeResult();
            if (objProvide == null)
            {
                objInvokeResult.ResultCode = "ProvideNull";
                objInvokeResult.ResultMessage = "保存失败";
                return Json(objInvokeResult, "text/plain");
            }
            if (objProvide.ParentId <= 0)
            {
                objInvokeResult.ResultCode = "ParentIdNull";
                objInvokeResult.ResultMessage = "保存失败";
                return Json(objInvokeResult, "text/plain");
            }
            PowerInfo objTarget = null;
            if (objProvide.Id <= 0)
            {
                if (objProvide.ControllerName.IsNoNull() && objProvide.ActionName.IsNoNull())
                {
                    bool isPowerExist = objBizPowerInfo.Any("ControllerName=@ControllerName AND ActionName=@ActionName AND AreaName=@AreaName", "ControllerName,ActionName,AreaName".CreateSqlParameters(objProvide.ControllerName, objProvide.ActionName, objProvide.AreaName.SetNullToDefaultValue(string.Empty)));
                    if (isPowerExist)
                    {
                        objInvokeResult.ResultCode = "PowerExist";
                        objInvokeResult.ResultMessage = string.Format("控制器名称{0}，Action名称{1}已存在", objProvide.ControllerName, objProvide.ActionName);
                        return Json(objInvokeResult, "text/plain");
                    }
                }
                objBizPowerInfo.ExecuteTransation(() =>
                {
                    List<PowerInfo> objList = new List<PowerInfo>();

                    objTarget = new PowerInfo();
                    Save(objTarget, objProvide);
                    objTarget.PowerCode = Guid.NewGuid().ToString();
                    objTarget.CreateDate = DateTime.Now;

                    var objParent = objBizPowerInfo.GetRecord(objTarget.ParentId);
                    objTarget.Depth = objParent.Depth + 1;
                    objTarget.Id = objBizPowerInfo.Add(objTarget);

                    objTarget.IDPath = objParent.IDPath + objTarget.Id + ",";
                    objTarget.SortIndex = objTarget.Id;
                    objBizPowerInfo.Update(objTarget);

                    objList.Add(objTarget);

                    if (objParent.HasChild != 1)
                    {
                        objParent.HasChild = 1;
                        objBizPowerInfo.Update(objParent);

                        objList.Add(objParent);
                    }

                    //写入Redis
                    if (IsCheckUserPowerRedis)
                    {
                        objBizPowerInfo.StoreAll(objList, PowerVariable.ProviderName, PowerVariable.Db);
                    }
                });
            }
            else
            {
                objTarget = objBizPowerInfo.GetRecord(objProvide.Id);
                if (objTarget == null)
                {
                    objInvokeResult.ResultCode = "DataNull";
                    objInvokeResult.ResultMessage = "保存失败";
                    return Json(objInvokeResult, "text/plain");
                }
                Save(objTarget, objProvide);
                objBizPowerInfo.Update(objTarget);

                //写入Redis
                if (IsCheckUserPowerRedis)
                {
                    objBizPowerInfo.Store(objTarget, PowerVariable.ProviderName, PowerVariable.Db);
                }
            }
            objInvokeResult.ResultCode = "Success";
            objInvokeResult.ResultMessage = "保存成功";
            objInvokeResult.Data = objTarget.Id;
            return Json(objInvokeResult, "text/plain");
        }
        /// <summary>
        /// 权限删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Delete(string id)
        {
            InvokeResult objInvokeResult = new InvokeResult();
            if (id.IsNull())
            {
                objInvokeResult.ResultCode = "IDNull";
                objInvokeResult.ResultMessage = "请先选择一条数据";
                return Json(objInvokeResult, "text/plain");
            }
            UserProcess objUserProcess = new UserProcess();
            objInvokeResult = objUserProcess.DeletePowers(id.Split(',').Select(c => Convert.ToInt64(c)).ToList());
            return Json(objInvokeResult, "text/plain");
        }
        /// <summary>
        /// 快速添加
        /// </summary>
        /// <returns></returns>
        public ActionResult QuickAdd()
        {
            return View();
        }
        /// <summary>
        /// 快速添加-保存
        /// </summary>
        /// <param name="powerId"></param>
        /// <param name="buttonIds"></param>
        /// <param name="controllerName"></param>
        /// <param name="areaName"></param>
        /// <returns></returns>
        public ActionResult AddPowers(long powerId, string buttonIds, string controllerName, string areaName)
        {
            PowerProcess objPowerProcess = new PowerProcess();
            return Json(objPowerProcess.AddPowers(powerId, buttonIds, controllerName, areaName), "text/plain");
        }
        /// <summary>
        /// 权限排序
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public ActionResult SortPowers(long parentId)
        {
            return View(objBizPowerInfo.GetList("ParentId=" + parentId, "SortIndex asc"));
        }
        /// <summary>
        /// 权限排序-保存
        /// </summary>
        /// <param name="powerIds"></param>
        /// <returns></returns>
        public ActionResult SaveSort(string powerIds)
        {
            PowerProcess objPowerProcess = new PowerProcess();
            return Json(objPowerProcess.SaveSort(powerIds), "text/plain");
        }
        /// <summary>
        /// 权限移动
        /// </summary>
        /// <returns></returns>
        public ActionResult MovePowers()
        {
            return View();
        }
        /// <summary>
        /// 权限移动-保存
        /// </summary>
        /// <param name="targetId"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public ActionResult SaveMove(long targetId, long parentId)
        {
            PowerProcess objPowerProcess = new PowerProcess();
            return Json(objPowerProcess.SaveMove(targetId, parentId), "text/plain");
        }
        /// <summary>
        /// 权限复制
        /// </summary>
        /// <returns></returns>
        public ActionResult CopyPower()
        {
            return View();
        }
        /// <summary>
        /// 权限复制-保存
        /// </summary>
        /// <param name="targetId"></param>
        /// <param name="parentId"></param>
        /// <param name="copyNumber"></param>
        /// <returns></returns>
        public ActionResult SaveCopy(long targetId, long parentId, int copyNumber)
        {
            PowerProcess objPowerProcess = new PowerProcess();
            return Json(objPowerProcess.SaveCopy(targetId, parentId, copyNumber), "text/plain");
        }
        /// <summary>
        /// 同步Redis缓存 
        /// </summary>
        /// <returns></returns>
        public ActionResult SyncRedis()
        {
            InvokeResult objInvokeResult = new InvokeResult();
            if (IsCheckUserPowerRedis)
            {
                bool flag = true;
                int pageIndex = 0;
                List<PowerInfo> objPowerInfoList = null;
                while (flag)
                {
                    objPowerInfoList = objBizPowerInfo.GetPageList(pageIndex, 50);
                    if (objPowerInfoList.IsNull())
                    {
                        flag = false;
                        break;
                    }
                    objBizPowerInfo.StoreAll(objPowerInfoList, PowerVariable.ProviderName, PowerVariable.Db);
                    pageIndex++;
                }
            }
            objInvokeResult.ResultMessage = "同步成功";
            return Json(objInvokeResult);
        }
        void Save(PowerInfo objTarget, PowerInfo objProvide)
        {
            objTarget.PowerName = objProvide.PowerName.CutWord(64);
            objTarget.ParentId = objProvide.ParentId;
            objTarget.AreaName = objProvide.AreaName.CutWord(64);
            objTarget.ControllerName = objProvide.ControllerName.CutWord(64);
            objTarget.ActionName = objProvide.ActionName.CutWord(64);
            objTarget.LinkUrl = objProvide.LinkUrl.CutWord(256);
            objTarget.PowerType = objProvide.PowerType;
            objTarget.Position = objProvide.Position;
            objTarget.Execution = objProvide.Execution.CutWord(64);
            objTarget.Icon = objProvide.Icon.CutWord(64);
            objTarget.IsDisplay = objProvide.IsDisplay;
        }

    }
}
